package wendyeq.iweb.blog.web.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import wendyeq.iweb.blog.pojo.Article;
import wendyeq.iweb.blog.service.IArticleService;
import wendyeq.iweb.blog.service.ICategoryService;
import wendyeq.iweb.blog.service.ICommentService;
import wendyeq.iweb.blog.service.ITagsService;
import wendyeq.iweb.blog.util.spider.Spider;
import wendyeq.iweb.blog.util.spider.SpiderConfig;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gson.Gson;

@Controller("articleController")
@RequestMapping("/admin/article/")
public class ArticleController {
	private static final Logger logger = Logger
	.getLogger(ArticleController.class);

	@Resource(name="articleServiceImpl")
	private IArticleService articleService;
	@Resource(name="categoryServiceImpl")
	private ICategoryService categoryService;
	@Resource(name="commentServiceImpl")
	private ICommentService commentService;
	@Resource(name="tagsServiceImpl")
	private ITagsService tagsService;

	public void makeSidebar(HttpServletRequest request , ModelMap model){
		model.addAttribute("categorys",this.categoryService.findAll());
		model.addAttribute("comments",this.commentService.findByPage(0, 10));
		model.addAttribute("tags", this.tagsService.findAll());
	}
	/***
	 * 访问url  http://localhost:8888/admin/article/add/
	 * */
	@RequestMapping("add")
	public String addArticle(HttpServletRequest request, ModelMap model) {
		model.addAttribute("categorys", this.categoryService.findAll());
		model.addAttribute("tags", this.tagsService.findAll());
		logger.warn(this.tagsService.findAll().size());
		//返回对应ftl
		return "admin/article";
	}

	@RequestMapping("post")
	public String postArticle(@RequestParam String title,@RequestParam String alias,
			@RequestParam String content, @RequestParam String categoryName,
			@RequestParam String isComment, 
			HttpServletRequest request, ModelMap model) {
		logger.info("title="+title);
		String[] tags = request.getParameterValues("tags");//tags id
		Set<String> tagSet = new HashSet<String>();
		if(tags!=null)
			for (String t : tags) 
				tagSet.add(t);
		Article article = new Article(title, alias,content);
		article.setCategory(categoryName);
		article.setIsComment(new Boolean(isComment));
		article.setCreatedTime(new Date());
		article.setTags(tagSet);
		this.articleService.save(article);

		makeSidebar(request, model);
		return "admin/index";
	}

	@RequestMapping("spidertest")
	public String spidertest(HttpServletRequest request, ModelMap model) {
		model.addAttribute("categorys", this.categoryService.findAll());
		model.addAttribute("tags", this.tagsService.findAll());
		startSpider();
		return "admin/index";
	}
	/***
	 * param为栏目分类名称
	 * 返回当天该栏目的数据
	 * http://localhost:8888/admin/article/getjson/AsianNo
	 * */
	@RequestMapping("getjson/{param}")
	public String getJson(@PathVariable String param,HttpServletRequest request, ModelMap model) {
		logger.warn(this.tagsService.findAll().size());

		List<Article> al = articleService.findByDateCategory(param, new java.util.Date());
		logger.info("================================="+al.size());
		Gson g=new Gson();
		String res=g.toJson(al);
		model.addAttribute("res", res);
		return "/admin/articlebySpider";
	}
	@RequestMapping("postbyspider")
	public String postArticleBySpider(@RequestParam String title,
			@RequestParam String content, @RequestParam String categoryName,
			HttpServletRequest request, ModelMap model) {

		articleService.findByDateCategory("AsianNo", new java.util.Date());
		//		String bf= request.getParameter("batchfile");
		//		//判断是否批量插入数据
		//		if(bf!=null||"file".equals(bf)){
		//			this.articleService.saveOrUPdatebatch(bf);
		//		}else{
		//			logger.info("title="+title);
		//			Article article = new Article(title, "",content);
		//			article.setCategory(categoryName);
		//			article.setIsComment(false);
		//			this.articleService.save(article);	
		//		}
		makeSidebar(request, model);
		return "admin/index";
	}

	private void startSpider(){
		Properties props = null;
		try{
			InputStream in = getClass().getClassLoader().getResourceAsStream("Spider.properties"); 
			props = new Properties();
			props.load(in);
			in.close();
			SpiderConfig config = new SpiderConfig(props);
			Spider spider;
			spider = new Spider(config,articleService);
			spider.start();
		}catch(IOException ioe){
			logger.error("IO Exception caught reading config file: " + ioe.getMessage(), ioe);
		}

	}
	@RequestMapping("update/{id}")
	public String updateArticle(@PathVariable String id,
			HttpServletRequest request, ModelMap model) {
		logger.warn("do update "+ id);
		model.addAttribute("article", this.articleService.findById(id));
		model.addAttribute("categorys", this.categoryService.findAll());
		model.addAttribute("tags", this.tagsService.findAll());
		return "admin/updateArticle";
	}

	@RequestMapping("postUpdate/{id}")
	public String postUpdateArticle(@PathVariable String id, HttpServletRequest request,
			ModelMap model) {
		logger.warn("do postUpdate "+ id);
		String title = request.getParameter("title");
		String alias = request.getParameter("alias");
		String isComment = request.getParameter("isComment");
		String categoryName = request.getParameter("categoryName");
		String[] tags = request.getParameterValues("tags");
		String content = request.getParameter("content");
		logger.warn(title+"--" + isComment+"--"+ content);
		Article a= new Article(title,alias,content);
		a.setId(id);
		a.setIsComment(new Boolean(isComment));
		a.setCategory(categoryName);
		Set<String> tagSet = new HashSet<String>();
		if(tags!=null)
			for (String t : tags) 
				tagSet.add(t);
		a.setTags(tagSet);
		this.articleService.modify(a);
		makeSidebar(request, model);
		return "admin/index";
	}

	@RequestMapping("del/{id}")
	public String delArticle(@PathVariable String id,
			HttpServletRequest request, ModelMap model) {
		this.articleService.delete(id);
		makeSidebar(request, model);
		return "admin/index";
	}

	@RequestMapping("list/{page}")
	public String adminListArticle(@PathVariable int page, HttpServletRequest request, ModelMap model) {
		List<Article> articles = this.articleService.findAll();
		int artSize = articles.size();
		if(artSize<10){
			model.addAttribute("articles",articles );
		}else if(artSize-page*10>=0){
			model.addAttribute("articles",articles.subList((page-1)*10,page*10));
		}else {
			model.addAttribute("articles",articles.subList((page-1)*10,artSize));
		}
		model.addAttribute("artSize", artSize);
		model.addAttribute("page", page);
		return "/admin/articleList";
	}
//	/**
//	 * 用来验证用户是否可用
//	 * */
//	private boolean vaildUser(){
//		UserService userService = UserServiceFactory.getUserService();
//		User user = userService.getCurrentUser();
//		if(user!=null&&"chch1020@gmail.com".equals(user.getEmail())){
//			return true;
//		}else{
//			return false;
//		}
//
//	}
}